/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package luft27.zorcon.input;

import java.util.HashMap;
import java.util.Map;
import net.java.games.input.*;

/**
 *
 * @author amalikov
 */
public class InputDetector {

	public InputDetector() {
		contrmap = new HashMap<>();
		final Controller[] controllers = ControllerEnvironment.getDefaultEnvironment().getControllers();
		for (Controller controller : controllers) {
			controller.setEventQueueSize(0);
			controller.setEventQueueSize(32);
			controller.poll();
			if (controller.getType() == Controller.Type.KEYBOARD || controller.getType() == Controller.Type.STICK) {
				Map<Component, Float> compmap = new HashMap<>();
				Component[] components = controller.getComponents();
				for (Component component : components)
					compmap.put(component, component.getPollData());
				contrmap.put(controller, compmap);
			}
		}
	}
	
	public boolean detect() {
		boolean res = false;
		for (Controller controller : contrmap.keySet()) {
			controller.poll();
			EventQueue eq = controller.getEventQueue();
			Event event = new Event();
			while (eq.getNextEvent(event)) {
				float diff = event.getValue() - contrmap.get(controller).get(event.getComponent());
				if (Math.abs(diff) > DIFFERENCE || !event.getComponent().isAnalog()) {
					detectedController = controller;
					detectedComponent = event.getComponent();
					inverted = diff < 0;
					res = true;
				}
			}
		}
		
		return res;
	}
	
	public Controller getController() {
		return detectedController;
	}

	public Component getComponent() {
		return detectedComponent;
	}	
	
	public boolean getInverted() {
		return inverted;
	}
	
	private final static float DIFFERENCE = 0.3f;
	private final Map<Controller, Map<Component, Float>> contrmap;
	private Controller detectedController;
	private Component detectedComponent;
	private boolean inverted;
}

